﻿Imports CRM.BusinessLayer
Imports System.Text
Imports System.Windows.Forms
Imports System.Data

Partial Public Class frmFinances
    Dim m_strCharacter As String

    Private Sub btnClose_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnClose.Click
        Dim frmCRMMainDisplay As New frmCRMMainDisplay
        Dim myAccountsSummary As Accounts.AccountsSummary
        Try
            myAccountsSummary = Accounts.GetAccountsSummary(GlobalCRM.CurrentCaseID)
            frmCRMMainDisplay.DisplayAccountsSummary(myAccountsSummary)
        Catch ex As Exception
        Finally
            myAccountsSummary = Nothing
            frmCRMMainDisplay = Nothing
            Me.Close()
        End Try

    End Sub
    Private Enum LVWType
        Quoted = 1
        Invoiced = 2
        Payments = 3

    End Enum

    Private Sub frmFinances_KeyUp(ByVal sender As Object, ByVal e As System.Windows.Input.KeyEventArgs) Handles Me.KeyUp
        If e.Key = Key.Escape Then
            btnClose_Click(sender, e)
        End If
    End Sub
    Private Sub Finances_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Loaded
        Dim dt As DataTable
        'Dim chkAmount As Double
        Try
            GeneralTasks.ChangeTheme(Me)
            GeneralTasks.EnumerateandFill(Me.LogicalChildren)

            If Security._SecurityLevel = SecurityLevel.NormalUser Or Security._SecurityLevel = SecurityLevel.BranchManager Then
                btnAddCredit.IsEnabled = False
                btnCreditCharges.IsEnabled = False
                btnRefund.IsEnabled = False
                btnWriteOff.IsEnabled = False
                'btnDelete.Enabled = False
            Else
                btnAddCredit.IsEnabled = True
                btnCreditCharges.IsEnabled = True
                btnRefund.IsEnabled = True
                btnWriteOff.IsEnabled = True
                'btnDelete.Enabled = True
            End If
            Dim userInstance As Singleton = Singleton.Instance
            If Accounts.IssueRefundAccess(userInstance.CurrentConId) = 1 Then
                Me.btnRefund.IsEnabled = True
            Else
                Me.btnRefund.IsEnabled = False
            End If

            If Accounts.CreditChargesAccess(userInstance.CurrentConId) = 1 And Security._SecurityLevel = SecurityLevel.AdminUser Then
                Me.btnAddCredit.IsEnabled = True
                Me.btnCreditCharges.IsEnabled = True
            Else
                Me.btnAddCredit.IsEnabled = False
                Me.btnCreditCharges.IsEnabled = False
            End If

            Me.Title = "Financial Details for Case No: " & GlobalCRM.CurrentCaseID & " in " & CommonDataFunctions.GetCurrencyCodeDesc(GlobalCRM.CurrentCaseID)

            m_strCharacter = CommonDataFunctions.GetCurrencyCodeCharacter(GlobalCRM.CurrentCaseID)
            grpICharges.Header = "Invoiced Charges" & " : " & m_strCharacter
            grpQCharges.Header = "Quoted Charges" & " : " & m_strCharacter
            grpPayments.Header = "Payments" & " : " & m_strCharacter

            'dt = FormatCurrencyDataTable(CommonDataFunctions.GetSQLDatatable(Accounts.QuotedCharges(GlobalCRM.CurrentCaseID)), LVWType.Quoted)
            dt = CommonDataFunctions.GetSQLDatatable(Accounts.QuotedCharges(GlobalCRM.CurrentCaseID))

            DataBinding.BindListView(dt, Me.lvwQuoted)
            Me.FormatCurrencyCols(Me.lvwQuoted)
            dt = CommonDataFunctions.GetSQLDatatable(Accounts.InvoicedCharges(GlobalCRM.CurrentCaseID))
            'dt = FormatCurrencyDataTable(CommonDataFunctions.GetSQLDatatable(Accounts.InvoicedCharges(GlobalCRM.CurrentCaseID)), LVWType.Invoiced)
            DataBinding.BindListView(dt, Me.lvwInvoiced)
            Me.FormatCurrencyCols(Me.lvwInvoiced)
            dt = CommonDataFunctions.GetSQLDatatable(Accounts.Payments(GlobalCRM.CurrentCaseID))
            ' dt = FormatCurrencyDataTable(CommonDataFunctions.GetSQLDatatable(Accounts.Payments(GlobalCRM.CurrentCaseID)), LVWType.Payments)
            DataBinding.BindListView(dt, Me.lvwPayments)
            Me.FormatCurrencyCols(Me.lvwPayments)

            ' disable Invoice button if case is not yet initiated or has been cancelled
            Dim CaseInfo As New Cases.CaseInfo
            CaseInfo = Cases.GetCaseInfo(GlobalCRM.CurrentCaseID)
            'MsgBox(CaseInfo.CaseStatusId.ToString)


            'If CaseInfo.CaseStatusId >= 40 And CaseInfo.CaseStatusId <= 1000 Then
            '    'If CommonFunc.GetCase_Product_InvoiceInfo(CaseInfo.CaseId) = 1 Then
            '    '    Me.btnInvoice.Enabled = True
            '    '    Me.drpMethod.Enabled = True
            '    '    Me.drpMethod.SelectedIndex = 0
            '    'Else
            '    '    Me.btnInvoice.Enabled = False
            '    '    Me.drpMethod.Enabled = False
            '    'End If
            '    If GlobalCRM.CurrentCompanyID > 0 Then
            '        Me.btnInvoice.IsEnabled = True
            '        Me.drpMethod.IsEnabled = True
            '        Me.drpMethod.SelectedIndex = 0
            '    Else
            '        Me.btnInvoice.IsEnabled = False
            '        'Me.drpMethod.IsEnabled = False
            '    End If
            'Else
            '    Me.btnInvoice.IsEnabled = False
            '    'Me.drpMethod.IsEnabled = False
            'End If
            Me.btnInvoice.IsEnabled = True
            'If CaseInfo.CaseStatusId >= 100 And CaseInfo.CaseStatusId <= 1000 Then - changed to 40 because of the payment issue - 1.2.3 version of crm- 
            'If CaseInfo.CaseStatusId >= 100 And CaseInfo.CaseStatusId <= 1000 Then '- Changed back to 100 because os improper sales issue - 12/02/2009
            '    'If CaseInfo.CaseStatusId >= 40 And CaseInfo.CaseStatusId <= 1000 Then
            '    Me.btnInvoice.IsEnabled = True
            '    Me.drpMethod.IsEnabled = True
            '    Me.drpMethod.SelectedIndex = 0
            'Else
            '    Me.btnInvoice.IsEnabled = False
            '    'Me.drpMethod.IsEnabled = False
            'End If
            'If lvwQuoted.Items.Count = 0 Then
            '    btnProformaInv.IsEnabled = False

            'Else
            '    btnProformaInv.IsEnabled = True

            'End If
            'chkAmount = CDbl(lblQuoteGross.Content) - CDbl(lblPaidTotal.Content) > -1
            'If chkAmount > -1 And chkAmount < 1 Then
            'Me.btnInvoice.IsEnabled = False
            'End If
        Catch ex As Exception
            CommonFuncs.ErrorHandler(ex, "Finances_Load")
        Finally
            dt = Nothing
        End Try
    End Sub
    Private Function FormatCurrencyDataTable(ByVal dt As DataTable, ByVal type As LVWType) As DataTable
        'Dim stempDT As DataTable
        Try

        
            Dim dr As DataRow
            If Not dt Is Nothing Then
                If dt.Rows.Count > 0 Then
                    For i = 0 To dt.Rows.Count - 1
                        dr = dt.Rows(i)

                        Select Case type
                            Case LVWType.Quoted
                                dr.BeginEdit()
                                dr.Item("Charge_Amount") = CommonDataFunctions.FormatCurr(dr.Item("Charge_Amount"), m_strCharacter)
                                dr.Item("ChgGross") = CommonDataFunctions.FormatCurr(dr.Item("ChgGross"), m_strCharacter)
                                dr.Item("ChgIncome") = CommonDataFunctions.FormatCurr(dr.Item("ChgIncome"), m_strCharacter)
                                dr.Item("Charge_TPCost") = CommonDataFunctions.FormatCurr(dr.Item("Charge_TPCost"), m_strCharacter)
                                dr.EndEdit()
                            Case LVWType.Invoiced
                                dr.BeginEdit()
                                dr.Item("Charge_Amount") = CommonDataFunctions.FormatCurr(dr.Item("Charge_Amount"), m_strCharacter)
                                dr.Item("ChgGross") = CommonDataFunctions.FormatCurr(dr.Item("ChgGross"), m_strCharacter)
                                dr.Item("ChgIncome") = CommonDataFunctions.FormatCurr(dr.Item("ChgIncome"), m_strCharacter)
                                dr.Item("Charge_TPCost") = CommonDataFunctions.FormatCurr(dr.Item("Charge_TPCost"), m_strCharacter)
                                dr.EndEdit()
                            Case LVWType.Payments
                                dr.BeginEdit()
                                dr.Item("Payment_Amount") = CommonDataFunctions.FormatCurr(dr.Item("Payment_Amount"), m_strCharacter)
                                dr.EndEdit()
                        End Select


                    Next
                    Return dt
                Else : Return dt
                End If
            Else : Return dt
            End If
        Catch ex As Exception
            Return dt
        End Try
    End Function

    Private Sub btnAddCharge_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAddCharge.Click
        Dim frmAddCharge As New frmAddCharge
        With frmAddCharge
            ._Mode = frmAddCharge.Mode.ActualCharge
            ._ChargeType = frmAddCharge.ChargeType.Charge
            .ProductId = Cases.GetCaseInfo(GlobalCRM.CurrentCaseID).Productid
            .ShowDialog()
        End With

        DataBinding.BindListView(CommonDataFunctions.GetSQLDatatable(Accounts.QuotedCharges(GlobalCRM.CurrentCaseID)), Me.lvwQuoted)
        Me.FormatCurrencyCols(Me.lvwQuoted)
    End Sub

    Private Sub btnDefaults_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDefaults.Click
        If Accounts.LoadDefaultCharges(GlobalCRM.CurrentCaseID) Then
            DataBinding.BindListView(CommonDataFunctions.GetSQLDatatable(Accounts.QuotedCharges(GlobalCRM.CurrentCaseID)), Me.lvwQuoted)
            Me.FormatCurrencyCols(Me.lvwQuoted)
        End If
    End Sub

    Private Sub btnDelete_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDelete.Click

        If Company.GetAccountType(GlobalCRM.CurrentCompanyID) = 2 Then

            'SLA

            Dim myCompany As Company.CompanyInfo = Company.GetCompany(GlobalCRM.CurrentCompanyID)

            If myCompany.AccountManagerId = 0 Then
                CommonFuncs.DisplayMessage("No Account Manager set for this company, please speak to an admin", CommonDialog.CustomDialogIcons.Information, "Error")
                Exit Sub
            End If

            'do sec check and are they the Acc Manager
            If Not (Security.CheckSecurityAccess(61) = 1 Or GlobalCRM.CurrentConID = myCompany.AccountManagerId) Then
                'no access allowed
                CommonFuncs.DisplayMessage("You do not have the correct access rights to change these details, please speak to the Account manager about deleting charges for this SLA account", CommonDialog.CustomDialogIcons.Information, "SLA charges deletion error")
                Exit Sub
            End If
        Else

        End If
        'Is there anything to delete?
        If Me.lvwQuoted.Items.Count = 0 Then
            CommonFuncs.DisplayMessage("No quoted Charges to delete", CommonDialog.CustomDialogIcons.Information, "Error")
            Exit Sub
        End If


        Dim Msg As New StringBuilder
        Dim i As Integer
        Dim lvi As DataRowView
        'Dim lvi As System.Windows.Controls.ListViewItem

        'Have they selected anything?
        If Me.lvwQuoted.SelectedItems.Count = 0 Then
            'No, see if they want to invoice everything
            If MsgBox("No Charges selected, would you like to delete all the quoted charges?", vbYesNo + vbQuestion, "Error") <> MsgBoxResult.Yes Then
                Exit Sub
            End If

            'Set where clause for use bellow based on case id and the invoice ID beng zero

            'Get all the details for the event later

            For Each lvi In Me.lvwQuoted.Items
                'uncomment this - 
                'Msg.Append(lvi.itemarray(1).Text & " : " & m_strCharacter & lvi.SubItems(3).Text & " Net : " & m_strCharacter & lvi.SubItems(6).Text & " Gross : " & lvi.SubItems(2).Text & vbCrLf)
            Next

            If Accounts.DeleteCharges(GlobalCRM.CurrentCaseID, Msg.ToString, True) Then
                DataBinding.BindListView(CommonDataFunctions.GetSQLDatatable(Accounts.QuotedCharges(GlobalCRM.CurrentCaseID)), Me.lvwQuoted)
                Me.FormatCurrencyCols(Me.lvwQuoted)
            End If

        Else

            'Go through all the selected items in the listbox and construct a string of thier ID values to use in the where clase of the query bellow

            Dim Charges() As Long = Nothing

            For Each lvi In Me.lvwQuoted.SelectedItems
                ReDim Preserve Charges(i)
                'uncomment this - 
                Charges(i) = lvi.Row.ItemArray(0).ToString

                'Get details for the event
                'uncomment this - 
                Msg.Append(lvi.Row.ItemArray(1).ToString & " : " & m_strCharacter & lvi.Row.ItemArray(3).ToString & " Net : " & m_strCharacter & lvi.Row.ItemArray(6).ToString & " Gross : " & lvi.Row.ItemArray(2).ToString & vbCrLf)

                i += 1
            Next

            If Accounts.DeleteCharges(GlobalCRM.CurrentCaseID, Msg.ToString, False, Charges) Then
                DataBinding.BindListView(CommonDataFunctions.GetSQLDatatable(Accounts.QuotedCharges(GlobalCRM.CurrentCaseID)), Me.lvwQuoted)
                Me.FormatCurrencyCols(Me.lvwQuoted)
            End If

        End If

    End Sub

    Public Sub FormatCurrencyCols(ByRef AnyListView As System.Windows.Controls.ListView)

        'Dim li As ListViewItem
        'Dim si As ListViewItem.ListViewSubItem
        'Dim i As Integer

        'For Each li In AnyListView.Items

        '    i = 0

        '    For Each si In li.SubItems

        '        If AnyListView.Name.ToUpper = "LVWQUOTED" Then

        '            Select Case i
        '                Case 3, 5, 6, 7

        '                    si.Text = CommonDataFunctions.FormatCurr(si.Text, m_strCharacter)

        '            End Select
        '        ElseIf AnyListView.Name.ToUpper = "LVWINVOICED" Then

        '            Select Case i
        '                Case 4, 6, 7, 8

        '                    si.Text = CommonDataFunctions.FormatCurr(si.Text, m_strCharacter)

        '            End Select

        '        ElseIf AnyListView.Name.ToUpper = "LVWPAYMENTS" Then

        '            Select Case i
        '                Case 4

        '                    si.Text = CommonDataFunctions.FormatCurr(si.Text, m_strCharacter)

        '            End Select


        '        End If

        '        i += 1

        '    Next

        'Next

        Me.CalculateTotals(AnyListView)

    End Sub

    Private Sub CalculateTotals(ByVal AnyListView As System.Windows.Controls.ListView)

        Dim lvi As DataRowView
        'Dim lvi As System.Windows.Controls.ListViewItem
        Dim strNet As String, strGross As String

        If AnyListView.Name.ToUpper = "LVWQUOTED" Then

            'Calc net sub total

            Dim Net As Double, Gross As Double


            For Each lvi In AnyListView.Items
                'uncomment this - 

                strNet = lvi.Row.ItemArray(3).ToString
                'uncomment this - 
                strGross = lvi.Row.ItemArray(7).ToString

                Net += CommonDataFunctions.GetCurrValue(strNet, m_strCharacter)
                Gross += CommonDataFunctions.GetCurrValue(strGross, m_strCharacter)
            Next

            Me.lblQuoteNet.Content = CommonDataFunctions.FormatCurr(Net, m_strCharacter)
            Me.lblQuoteGross.Content = CommonDataFunctions.FormatCurr(Gross, m_strCharacter)

        ElseIf AnyListView.Name.ToUpper = "LVWINVOICED" Then

            Dim Net, Gross As Decimal

            For Each lvi In AnyListView.Items
                'uncomment this - 
                strNet = lvi.Row.ItemArray(4).ToString
                'uncomment this - 
                strGross = lvi.Row.ItemArray(8).ToString

                Net += CommonDataFunctions.GetCurrValue(strNet, m_strCharacter)
                Gross += CommonDataFunctions.GetCurrValue(strGross, m_strCharacter)
            Next

            Me.lblInvoiceNet.Content = CommonDataFunctions.FormatCurr(Net, m_strCharacter)
            Me.lblInvoiceGross.Content = CommonDataFunctions.FormatCurr(Gross, m_strCharacter)

        ElseIf AnyListView.Name.ToUpper = "LVWPAYMENTS" Then

            Dim Total As Decimal

            For Each lvi In AnyListView.Items
                'uncomment this - 
                Total += CommonDataFunctions.GetCurrValue(lvi.Row.ItemArray(4).ToString, m_strCharacter)
            Next

            Me.lblPaidTotal.Content = CommonDataFunctions.FormatCurr(Total, m_strCharacter)

        End If

        If IsNumeric(CommonDataFunctions.GetCurrValue(Me.lblInvoiceGross.Content, m_strCharacter)) And IsNumeric(CommonDataFunctions.GetCurrValue(Me.lblPaidTotal.Content, m_strCharacter)) Then
            Me.lblCaseBalance.Content = CommonDataFunctions.FormatCurr(CommonDataFunctions.GetCurrValue(Me.lblInvoiceGross.Content, m_strCharacter) - CommonDataFunctions.GetCurrValue(Me.lblPaidTotal.Content, m_strCharacter), m_strCharacter)
        End If

    End Sub

    Private Sub btnAddCredit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAddCredit.Click
        Dim frmAddCharge As New frmAddCharge
        With frmAddCharge
            ._Mode = frmAddCharge.Mode.ActualCharge
            ._ChargeType = frmAddCharge.ChargeType.Credit
            .ProductId = Cases.GetCaseInfo(GlobalCRM.CurrentCaseID).Productid
            .ShowDialog()
        End With

        DataBinding.BindListView(CommonDataFunctions.GetSQLDatatable(Accounts.QuotedCharges(GlobalCRM.CurrentCaseID)), Me.lvwQuoted)
        Me.FormatCurrencyCols(Me.lvwQuoted)

    End Sub

    Private Sub btnInvoice_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnInvoice.Click

        'Is there anything to invoice?
        Dim tsk As New TasksEvents
        Try


            If Me.lvwQuoted.Items.Count = 0 Then
                CommonFuncs.DisplayMessage("No quoted Charges to invoice", CommonDialog.CustomDialogIcons.Information, "Error")
                Exit Sub
            End If

            'check if we have an invoice address

            Dim SQL As New StringBuilder
            Dim InvAddress As Boolean
            Dim ClientType As String
            Dim InvoiceNo As Long
            Dim InvoiceDue As Date
            Dim Charges() As Long = Nothing
            Dim InvoiceAll As Boolean
            Dim strSQL As String
            Dim lngDocStore As Long

            Dim caseStage As Cases.CaseStage = Cases.GetCaseStage(GlobalCRM.CurrentCaseID)

            If (caseStage.StageNumber < 3) Then
                CommonFuncs.DisplayMessage("Send CCL first. Cannot generate an invoice", CommonDialog.CustomDialogIcons.Information, "Error")
                Exit Sub
            End If

            If GlobalCRM.CurrentCompanyID > 0 Then
                InvAddress = Company.HasInvoiceAddress(GlobalCRM.CurrentCompanyID)
                ClientType = "Company"
            Else
                InvAddress = People.HasInvoiceAddress(GlobalCRM.CurrentCandidateID)
                ClientType = "Candidate"
            End If

            If Not InvAddress Then
                CommonFuncs.DisplayMessage("No Invoice address has been defined for this " & ClientType & ", cannot generate an invoice", CommonDialog.CustomDialogIcons.Information, "Error")
                Exit Sub
            End If

            'Have they selected anything?
            If Me.lvwQuoted.SelectedItems.Count = 0 Then
                'No, see if they want to invoice everything
                If MsgBox("No Charges selected to Invoice, would you like to add all outstanding charges?", vbYesNo + vbExclamation, "Error") <> MsgBoxResult.Yes Then
                    Exit Sub
                End If
                InvoiceAll = True
            Else

                'Go through all the selected items in the listbox and construct a string of thier ID values to use in the where clase of the query bellow

                'Dim lvi As System.Windows.Controls.ListViewItem
                Dim lvi As DataRowView

                Dim i As Integer

                For Each lvi In Me.lvwQuoted.SelectedItems
                    ReDim Preserve Charges(i)

                    'uncomment this - 
                    Charges(i) = lvi.Row.ItemArray(0).ToString
                    i += 1
                Next

            End If

            'Set up data for use below
            If GlobalCRM.CurrentCompanyID > 0 Then
                'Get the number of days credit based on the account type of the company
                InvoiceDue = Accounts.GetInvoiceDueDate(GlobalCRM.CurrentCompanyID)
            Else
                InvoiceDue = Now
            End If

            'Create an Invoice
            InvoiceNo = Accounts.CreateInvoice(GlobalCRM.CurrentCaseID, GlobalCRM.CurrentCompanyID, GlobalCRM.CurrentCandidateID, InvoiceDue, GlobalCRM.CurrentConName)
            If InvoiceNo = 0 Then
                CommonFuncs.DisplayMessage("Error creating invoice!", CommonDialog.CustomDialogIcons.Information, "Error")
                Exit Sub
            End If
            GlobalCRM.CurrentInvoiceId = InvoiceNo
            'Add the charges to the invoice using where clause from above
            If Not Accounts.UpdateChargesAsInvoiced(GlobalCRM.CurrentCaseID, InvoiceNo, Charges, InvoiceAll) Then
                Exit Sub
            End If

            'Put a copy of the invoice in the Docstore and print if requested.
            If Me.drpMethod.SelectedIndex > 0 Then  ' Print


                lngDocStore = Accounts.Gblfunc_Print_Invoice(InvoiceNo, Me.drpMethod.SelectedIndex)

                strSQL = "Update A_Invoices set Invoice_DocStoreID = " & lngDocStore & " Where Invoice_ID = " & InvoiceNo
                CommonDataFunctions.ExecuteSQL(strSQL)

                ''Add Event
                Call tsk.GblFunc_Add_Event("Invoice Generated", "Invoice no. " & InvoiceNo & " created. Docstore no. " & lngDocStore, 1, GlobalCRM.CurrentCaseID, 1)

                If GlobalCRM.CurrentCompanyID <> 0 Then
                    Call tsk.GblFunc_Add_Event("Invoice Generated", "Invoice no. " & InvoiceNo & " created for case no. " & GlobalCRM.CurrentCaseID & ".  Docstore no. " & lngDocStore, 1, GlobalCRM.CurrentCompanyID, 3)

                    Exit Sub
                End If
            End If

            RefreshLists()
        Catch ex As Exception
        Finally
            tsk = Nothing
        End Try
    End Sub

    Public Sub RefreshLists()
        'refresh all three lists and the totals
        Try

        
            DataBinding.BindListView(CommonDataFunctions.GetSQLDatatable(Accounts.QuotedCharges(GlobalCRM.CurrentCaseID)), Me.lvwQuoted)
            Me.FormatCurrencyCols(Me.lvwQuoted)

            DataBinding.BindListView(CommonDataFunctions.GetSQLDatatable(Accounts.InvoicedCharges(GlobalCRM.CurrentCaseID)), Me.lvwInvoiced)
            Me.FormatCurrencyCols(Me.lvwInvoiced)

            DataBinding.BindListView(CommonDataFunctions.GetSQLDatatable(Accounts.Payments(GlobalCRM.CurrentCaseID)), Me.lvwPayments)
            Me.FormatCurrencyCols(Me.lvwPayments)
        Catch ex As Exception
            CommonFuncs.ErrorHandler(ex, "frmFinances : RefreshLists")
        End Try
    End Sub

    Private Sub btnCreditCharges_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCreditCharges.Click
        ' add a negative charge for each selected invoiced charge
        Dim tsk As New TasksEvents
        Try


            Dim StrCharges As String = String.Empty
            Dim StrMsg As String = String.Empty
            Dim StrSQL As String = String.Empty

            If Me.lvwInvoiced.Items.Count = 0 Then
                CommonFuncs.DisplayMessage("No invoiced Charges to credit", CommonDialog.CustomDialogIcons.Information, "Error")
                Exit Sub
            End If

            If Me.lvwInvoiced.SelectedItems.Count = 0 Then
                CommonFuncs.DisplayMessage("Please select the invoiced Charges you wish to credit", CommonDialog.CustomDialogIcons.Information, "Error")
                Exit Sub
            End If

            'Go through all the selected items in the listbox and construct a string of their ID values to use in the where clase of the query below
            'Dim lvi As System.Windows.Controls.ListViewItem
            Dim lvi As DataRowView

            For Each lvi In Me.lvwInvoiced.SelectedItems
                StrCharges = StrCharges & lvi.Row.ItemArray(0).ToString & ","
                StrMsg = StrMsg & "ChargeID: " & lvi.Row.ItemArray(0).ToString & ", Net: " & m_strCharacter & lvi.Row.ItemArray(4).ToString & ", VAT: " & lvi.Row.ItemArray(5).ToString & " TP : " & lvi.Row.ItemArray(6).ToString & ", Gross: " & lvi.Row.ItemArray(8).ToString & vbCrLf
            Next

            StrCharges = Mid(StrCharges, 1, (Len(StrCharges) - 1))

            'Set up query to copy selected charges with amounts reversed, 'credit' put in front of the type and cat set to 4 (credit)
            StrSQL = "INSERT INTO A_Charges"
            StrSQL = StrSQL & " (Charge_Type, Charge_EnteredBy, Charge_CompanyID, Charge_PersonID, Charge_CaseID, Charge_VAT, Charge_Amount, Charge_TPCost,"
            StrSQL = StrSQL & " Charge_Category, Charge_Desc)"
            StrSQL = StrSQL & " SELECT     'Credit: (' + Charge_Type + ')' AS Type, '" & GlobalCRM.CurrentConName & "' AS Cons, Charge_CompanyID, Charge_PersonID, Charge_CaseID, Charge_VAT,"
            StrSQL = StrSQL & " Charge_Amount * - 1 AS Amount, Charge_TPCost * - 1 AS TPCost, Charge_Category, 'Credited charge' AS [Desc]"
            StrSQL = StrSQL & " FROM A_Charges"
            StrSQL = StrSQL & " WHERE Charge_ID IN (" & StrCharges & ")"

            ' add the credit charges
            If CommonDataFunctions.ExecuteSQL(StrSQL) = False Then
                CommonFuncs.DisplayMessage("Error - Could not add the credit charges.", CommonDialog.CustomDialogIcons.Information, "Error")
                Exit Sub
            End If

            ' log an event
            tsk.GblFunc_Add_Event("Charges Credited", StrMsg, TasksEvents.EventStatus.SingleEvent, GlobalCRM.CurrentCaseID, TasksEvents.EventTypes.EventCase)

            ' deselect the invoices
            For Each lvi In Me.lvwInvoiced.SelectedItems
                ' lvi.IsSelected = False
            Next

            RefreshLists()
        Catch ex As Exception
        Finally
            tsk = Nothing
        End Try
    End Sub

    Private Sub btnAddPayment_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAddPayment.Click
        Dim invoicedamount As Long = Convert.ToDouble(lblInvoiceNet.Content)
        If invoicedamount <= 0.0 Then
            CommonFuncs.DisplayMessage("Please invoice the charge before making a payment.", CommonDialog.CustomDialogIcons.Information, "No Invoiced Charges")
            Exit Sub
        End If
        Dim frmAddPayment As New frmAddPayment
        frmAddPayment.PaymentTypeGroup = 1
        GlobalCRM.QuoteGross = lblQuoteGross.Content
        GlobalCRM.QuoteNet = lblQuoteNet.Content
        GlobalCRM.InvGross = lblInvoiceGross.Content
        GlobalCRM.InvNet = lblInvoiceNet.Content
        GlobalCRM.Balance = lblCaseBalance.Content
        GlobalCRM.Payment = lblPaidTotal.Content
        frmAddPayment.ShowDialog()

        ''fill the payments done 
        RefreshLists()
    End Sub

    Private Sub btnReprintReceipt_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnReprintReceipt.Click
        Dim tsk As New TasksEvents
        Try
            If Me.lvwPayments.SelectedItems.Count = 0 Then
                CommonFuncs.DisplayMessage("Please select a payment to print", CommonDialog.CustomDialogIcons.Information, "Error")
                Exit Sub
            End If

            GlobalCRM.CurrentPaymentId = Me.lvwPayments.SelectedItem.row.itemarray(0).ToString
            Call GenerateReceipt()

            Call tsk.GblFunc_Add_Event("Receipt Reprinted", "Receipt no. " & Me.lvwPayments.SelectedItem.row.itemarray(0).ToString & " (" & m_strCharacter & Me.lvwPayments.SelectedItem.row.itemarray(4).ToString & " : " & Me.lvwPayments.SelectedItem.row.itemarray(3).ToString & ")reprinted", TasksEvents.EventStatus.SingleEvent, GlobalCRM.CurrentCaseID, TasksEvents.EventTypes.EventCase)

        Catch ex As System.Exception
            CommonFuncs.DisplayMessage(ex.Message, CommonDialog.CustomDialogIcons.Information, "Error")
        Finally
            tsk = Nothing
        End Try
    End Sub

    Private Sub btnRefund_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRefund.Click
        Dim frmAddPayment As New frmAddPayment
        'frmAddPayment.PaymentTypeGroup = 2
        frmAddPayment.PaymentTypeGroup = 1
        frmAddPayment.ShowDialog()
        RefreshLists()
    End Sub

    Public Shared Function GenerateReceipt() As Boolean
        Dim Rpt As Object = Nothing
        Try
            Rpt = New PrivateReceipt

            If GlobalCRM.CurrentCompanyID = 0 Then
                Rpt = New PrivateReceipt
                Rpt.setdatasource(ReportCRM.GetReportData(ReportCRM.ReportType.PrivateReceipt))
            Else
                Rpt = New CorporateReceipt
                Rpt.setdatasource(ReportCRM.GetReportData(ReportCRM.ReportType.CorporateReceipt))
            End If

            Dim c As CrystalDecisions.CrystalReports.Engine.ReportDocument

            c = Rpt

            'c.ExportToDisk(CrystalDecisions.Shared.ExportFormatType.WordForWindows, "c:\crap\exporttest.doc")
            'Uncomment the following line when building to live.
            c.PrintToPrinter(1, True, 1, 1)
            Return True
        Catch ex As Exception
            Return False
        Finally
            Rpt = Nothing
        End Try
    End Function

    Private Sub lvwInvoiced_MouseDoubleClick(ByVal sender As Object, ByVal e As System.Windows.Input.MouseButtonEventArgs) Handles lvwInvoiced.MouseDoubleClick
        Dim Msg As StringBuilder
        If lvwInvoiced.SelectedItems.Count = 1 Then
            Dim dt As DataTable
            dt = Accounts.GetInvoiceDetails(lvwInvoiced.Items(0).row.itemarray(1).ToString)
            If Not dt Is Nothing Then
                If dt.Rows.Count > 0 Then
                    Msg = New StringBuilder
                    With Msg
                        .Append("Invoiced Date : " & dt.Rows(0).Item("invoice_date")).AppendLine()
                        .Append("Invoiced Due Date : " & dt.Rows(0).Item("invoice_datedue")).AppendLine()
                        .Append("Invoiced By : " & dt.Rows(0).Item("Invoice_enteredby")).AppendLine()
                    End With
                    CommonFuncs.DisplayMessage(Msg.ToString, CommonDialog.CustomDialogIcons.Information, "Summary")
                End If
            End If
        End If
    End Sub

    Private Sub lvwPayments_MouseDoubleClick(ByVal sender As Object, ByVal e As System.Windows.Input.MouseButtonEventArgs) Handles lvwPayments.MouseDoubleClick
        'Dim Msg As StringBuilder
        'If lvwPayments.SelectedItems.Count = 1 Then
        '    Dim dt As DataTable
        '    dt = Accounts.GetPaymentDetails(lvwInvoiced.Items(0).row.itemarray(0).ToString)
        '    If Not dt Is Nothing Then
        '        If dt.Rows.Count > 0 Then
        '            Msg = New StringBuilder
        '            With Msg
        '                .Append("Invoiced Date : " & dt.Rows(0).Item("invoice_date")).AppendLine()
        '                .Append("Invoiced Due Date : " & dt.Rows(0).Item("invoice_datedue")).AppendLine()
        '                .Append("Invoiced By : " & dt.Rows(0).Item("Invoice_enteredby")).AppendLine()
        '            End With
        '            MsgBox(Msg.ToString, MsgBoxStyle.Information, "Summary")
        '        End If
        '    End If
        'End If
    End Sub

    
    Private Sub btnProformaInv_Click(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnProformaInv.Click
        Dim SQL As New StringBuilder
        Dim InvAddress As Boolean
        Dim ClientType As String

        Dim Charges() As Long = Nothing

        If GlobalCRM.CurrentCompanyID > 0 Then
            InvAddress = Company.HasInvoiceAddress(GlobalCRM.CurrentCompanyID)
            ClientType = "Company"
        Else
            InvAddress = People.HasInvoiceAddress(GlobalCRM.CurrentCandidateID)
            ClientType = "Candidate"
        End If

        If Not InvAddress Then
            'MsgBox("No Invoice address has been defined for this " & ClientType & ", cannot generate an invoice", MsgBoxStyle.Exclamation, "Error")
            CommonFuncs.DisplayMessage("No Invoice address has been defined for this " & ClientType & ", cannot generate an invoice", CommonDialog.CustomDialogIcons.Information, "Error")
            Exit Sub
        End If
        If Me.drpMethod.SelectedIndex = -1 Then
            CommonFuncs.DisplayMessage("Please select method from the drop down list.", CommonDialog.CustomDialogIcons.Information, "Select")
            Me.drpMethod.Focus()
            Exit Sub
        End If
        'Have they selected anything?
        If Me.lvwQuoted.SelectedItems.Count = 0 Then
            'No, see if they want to invoice everything
            If MsgBox("No Charges selected to Invoice, would you like to add all outstanding charges?", vbYesNo + vbExclamation, "Error") <> MsgBoxResult.Yes Then
                Exit Sub
            End If
            ' InvoiceAll = True
        Else

            'Go through all the selected items in the listbox and construct a string of thier ID values to use in the where clase of the query bellow
            If Me.drpMethod.SelectedIndex > 0 Then  ' Print
                'RefreshLists()
            Else
                Dim intStage As Integer
                Dim CustType As Integer
                If GlobalCRM.CurrentCompanyID > 0 Then
                    CustType = 2
                Else
                    CustType = 1
                End If
                Try
                    Dim CrystRpt As New CrystalDecisions.CrystalReports.Engine.ReportDocument
                    Dim DocstoreId As Long
                    Dim DocFileName As String

                    SQL = New StringBuilder

                    intStage = 9

                    If CustType = 2 Then
                        If drpMethod.Text = "Email" Then
                            Dim Rpt As New NormalProformaIndiv_Upd
                            'Dim Rpt As New ProformaIndiv_Upd
                            'Dim Rpt As New ProformaComp
                            Dim dt As DataTable = ReportCRM.GetReportData(ReportCRM.ReportType.ProformaCompany)
                            Rpt.SetDataSource(dt)
                            If dt.Rows.Count > 0 Then
                                Rpt.SetDataSource(dt)
                                CrystRpt = Rpt
                            Else
                                'MsgBox("No data in Proforma. Hence Performa is not generated. Please contact IT for more information", MsgBoxStyle.Exclamation, "Error")
                                CommonFuncs.DisplayMessage("No data in Proforma. Hence Performa is not generated. Please add the charges and generate the proforma", CommonDialog.CustomDialogIcons.Information, "Error")
                                Exit Try
                            End If
                        End If
                        If Me.drpMethod.Text = "Print" Then
                            Dim Rpt As New ProformaIndiv_Upd
                            Dim dt As DataTable = ReportCRM.GetReportData(ReportCRM.ReportType.NormalProformaCompany)
                            Rpt.SetDataSource(dt)
                            If dt.Rows.Count > 0 Then
                                Rpt.SetDataSource(dt)
                                CrystRpt = Rpt
                            Else
                                'MsgBox("No data in Proforma. Hence Performa is not generated. Please contact IT for more information", MsgBoxStyle.Exclamation, "Error")
                                CommonFuncs.DisplayMessage("No data in Proforma. Hence Performa is not generated. Please add the charges and generate the proforma", CommonDialog.CustomDialogIcons.Information, "Error")
                                Exit Try
                            End If
                        End If
                        If Me.drpMethod.Text = "H: Drive" Then
                            If MsgBox("Would you like to save the proforma in Global Visas letter head?", MsgBoxStyle.YesNo, "Proforma") = MsgBoxResult.Yes Then
                                Dim Rpt As New NormalProformaIndiv_Upd
                                Dim dt As DataTable = ReportCRM.GetReportData(ReportCRM.ReportType.ProformaCompany)
                                Rpt.SetDataSource(dt)
                                If dt.Rows.Count > 0 Then
                                    Rpt.SetDataSource(dt)
                                    CrystRpt = Rpt
                                Else
                                    'MsgBox("No data in Proforma. Hence Performa is not generated. Please contact IT for more information", MsgBoxStyle.Exclamation, "Error")
                                    CommonFuncs.DisplayMessage("No data in Proforma. Hence Performa is not generated. Please add the charges and generate the proforma", CommonDialog.CustomDialogIcons.Information, "Error")
                                    Exit Try
                                End If
                            Else
                                Dim Rpt As New ProformaIndiv_Upd

                                Dim dt As DataTable = ReportCRM.GetReportData(ReportCRM.ReportType.NormalProformaCompany)
                                Rpt.SetDataSource(dt)
                                If dt.Rows.Count > 0 Then
                                    Rpt.SetDataSource(dt)
                                    CrystRpt = Rpt
                                Else
                                    'MsgBox("No data in Proforma. Hence Performa is not generated. Please contact IT for more information", MsgBoxStyle.Exclamation, "Error")
                                    CommonFuncs.DisplayMessage("No data in Proforma. Hence Performa is not generated. Please add the charges and generate the proforma", CommonDialog.CustomDialogIcons.Information, "Error")
                                    Exit Try
                                End If
                            End If

                        End If
                    Else
                        If Me.drpMethod.Text = "Email" Then
                            'Dim Rpt As New ProformaIndiv
                            Dim Rpt As New NormalProformaIndiv_Upd
                            Dim dt As DataTable = ReportCRM.GetReportData(ReportCRM.ReportType.ProformaIndividual)
                            If dt.Rows.Count > 0 Then
                                Rpt.SetDataSource(dt)
                                CrystRpt = Rpt
                            Else
                                'MsgBox("No data in Proforma. Hence Performa is not generated. Please contact IT for more information", MsgBoxStyle.Exclamation, "Error")
                                CommonFuncs.DisplayMessage("No data in Proforma. Hence Performa is not generated. Please add the charges and generate the proforma", CommonDialog.CustomDialogIcons.Information, "Error")
                                Exit Try
                            End If
                        End If
                        If Me.drpMethod.Text = "Print" Then
                            'Dim Rpt As New NormalProformaIndiv
                            Dim Rpt As New ProformaIndiv_Upd
                            Dim dt As DataTable = ReportCRM.GetReportData(ReportCRM.ReportType.NormalProformaIndividual)
                            If dt.Rows.Count > 0 Then
                                Rpt.SetDataSource(dt)
                                CrystRpt = Rpt
                            Else
                                'MsgBox("No data in Proforma. Hence Performa is not generated. Please contact IT for more information", MsgBoxStyle.Exclamation, "Error")
                                CommonFuncs.DisplayMessage("No data in Proforma. Hence Performa is not generated. Please add the charges and generate the proforma", CommonDialog.CustomDialogIcons.Information, "Error")
                                Exit Try
                            End If
                        End If
                        If Me.drpMethod.Text = "H: Drive" Then
                            If MsgBox("Would you like to save the proforma in Global Visas letter head?", MsgBoxStyle.YesNo, "Proforma") = MsgBoxResult.Yes Then
                                'Dim Rpt As New ProformaIndiv
                                Dim Rpt As New NormalProformaIndiv_Upd
                                Dim dt As DataTable = ReportCRM.GetReportData(ReportCRM.ReportType.ProformaIndividual)
                                Rpt.SetDataSource(dt)
                                If dt.Rows.Count > 0 Then
                                    Rpt.SetDataSource(dt)
                                    CrystRpt = Rpt
                                Else
                                    'MsgBox("No data in Proforma. Hence Performa is not generated. Please contact IT for more information", MsgBoxStyle.Exclamation, "Error")
                                    CommonFuncs.DisplayMessage("No data in Proforma. Hence Performa is not generated. Please add the charges and generate the proforma", CommonDialog.CustomDialogIcons.Information, "Error")
                                    Exit Try
                                End If
                            Else
                                'Dim Rpt As New NormalProformaIndiv
                                Dim Rpt As New ProformaIndiv_Upd
                                Dim dt As DataTable = ReportCRM.GetReportData(ReportCRM.ReportType.NormalProformaIndividual)
                                Rpt.SetDataSource(dt)
                                If dt.Rows.Count > 0 Then
                                    Rpt.SetDataSource(dt)
                                    CrystRpt = Rpt
                                Else
                                    CommonFuncs.DisplayMessage("No data in Proforma. Hence Performa is not generated. Please add the charges and generate the proforma", CommonDialog.CustomDialogIcons.Information, "Error")
                                    'MsgBox("No data in Proforma. Hence Performa is not generated. Please contact IT for more information", MsgBoxStyle.Exclamation, "Error")
                                    Exit Try
                                End If
                            End If

                        End If
                    End If


                    If Me.drpMethod.Text = "Print" Then
                        intStage = 10
                        'goes in a docstore by itself as no way to combine it with letterpack store.

                        'DocstoreId = Letters.GblFunc_Create_DocStore("Proforma Invoice", "Printed", GlobalCRM.CurrentCaseID)

                        DocFileName = "C:\Database\Proforma_CaseID_" & GlobalCRM.CurrentCaseID & ".doc"

                        CrystRpt.ExportToDisk(CrystalDecisions.Shared.ExportFormatType.WordForWindows, DocFileName)
                        CrystRpt.PrintToPrinter(1, True, 1, 1)
                        'Letters.GblFunc_Add_FileToStore(DocFileName, "Proforma", DocstoreId)

                        Kill(DocFileName)
                        intStage = 11

                    ElseIf Me.drpMethod.Text = "Email" Then
                        'Stick it on the C: drive to be e-mailed and put a value in local attachments
                        intStage = 12
                        DocFileName = "c:\database\Proforma_CaseID_" & GlobalCRM.CurrentCaseID & ".pdf"

                        CrystRpt.ExportToDisk(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat, DocFileName)

                        'Letters.GblFunc_Add_FileToStore(DocFileName, "Proforma", DocstoreId)

                        GlobalCRM.LocalAttachments.AddAttachment("Proforma for case no. " & GlobalCRM.CurrentCaseID, DocFileName)

                        intStage = 13

                    ElseIf Me.drpMethod.Text = "H: Drive" Then
                        'Stick it on the H: drive
                        intStage = 14
                        DocFileName = "H:\Proforma_CaseNo_" & GlobalCRM.CurrentCaseID & ".pdf"
                        'oWordAppl = New Word.ApplicationClass

                        'Dim test As New WordAppl

                        'Dim TemplatePath As String = "C:\Database\crm2\a.dot"

                        'Dim DocumentPath As String = DocFileName

                        'test.Open(TemplatePath)

                        'test.FindAndReplacement("<<company>>", "JAYASEELAN")

                        'test.SaveAs(DocFileName)

                        'test.Quit()

                        'CrystRpt.ExportToStream(CrystalDecisions.Shared.ExportFormatType.NoFormat)

                        CrystRpt.ExportToDisk(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat, DocFileName)
                        'CrystRpt.SaveAs(DocFileName)
                        'Dim oDoc As Word.Document
                        'Dim range As Word.Range

                        'oDoc = GetObject("C:\Documents and Settings\v\Desktop\ss.doc")
                        'oDoc.Sections(1).Headers(Word.WdHeaderFooterIndex.wdHeaderFooterFirstPage).Range.InlineShapes.AddPicture("C:\Documents and Settings\v\Desktop\l.JPG")
                        'oDoc.SaveAs(FileName:=DocFileName)

                        'Dim exportOpts As New CrystalDecisions.Shared.ExportOptions 'export options for report
                        'Dim diskOpts As New CrystalDecisions.Shared.DiskFileDestinationOptions 'saving location options
                        'exportOpts = CrystRpt.ExportOptions

                        '' Set the export format.
                        'exportOpts.ExportFormatType = CrystalDecisions.[Shared].ExportFormatType.WordForWindows
                        'exportOpts.ExportDestinationType = CrystalDecisions.[Shared].ExportDestinationType.DiskFile

                        '' Set the disk file options.
                        'diskOpts.DiskFileName = "C:\Database\crm2\a.dot" 'specify template file here!
                        'exportOpts.DestinationOptions = diskOpts

                        '' Export the report.
                        'CrystRpt.Export() 'rpt1 is the name of my Crystal Report

                    End If

                    intStage = 15
                    If Me.drpMethod.Text = "Email" Then
                        intStage = 16
                        Me.Close()
                        Dim frmSendEmail As New frmSendEmail
                        With frmSendEmail
                            ' .InitialiseForm(GlobalCRM.CurrentCaseID, frmSendEmail.DataTypes.VisaCase, frmSendEmail.EmailType.Candidate)
                            '.MdiParent = frmMDIMain

                            If GlobalCRM.CurrentCompanyID > 0 Then
                                frmSendEmail.iEmailType = CommonDataFunctions.EmailType.Contact
                            Else
                                frmSendEmail.iEmailType = CommonDataFunctions.EmailType.Candidate
                            End If

                            .Show()
                        End With
                    End If
                    'done with the proforma
                Catch ex As Exception
                    CommonFuncs.ErrorHandler(ex, "frmFinances_ProformaError")
                    'MsgBox("Proforma Error. Please check your crystal reports", MsgBoxStyle.Critical, "Error")
                    CommonFuncs.DisplayMessage("There was an error generating the Proforma.Please check your crystal reports", CommonDialog.CustomDialogIcons.Information, "Error")
                End Try
            End If

        End If

    End Sub

    Private Sub btnWriteOff_Click(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnWriteOff.Click
        Dim tsk As New TasksEvents
        Dim singleObject As Singleton = Singleton.Instance
        Dim StrSQL As String
        Dim StrCharges As String = Me.lblCaseBalance.Content
        Dim caseBalance As Long = Convert.ToDecimal(StrCharges)
        If (caseBalance < 0) Then
            CommonFuncs.DisplayMessage("Error - Could not write off charges as there is no outstanding balance on customer to pay!", CommonDialog.CustomDialogIcons.Information, "Error")
            Exit Sub
        End If
        Dim chargeId As Long = Accounts.CreateCharge(GlobalCRM.CurrentCaseID, GlobalCRM.CurrentCandidateID, 1, "Write Off Charges", singleObject.CurrentConName, GlobalCRM.CurrentCompanyID, 0, StrCharges, 0, -1)
        If (chargeId <> 0) Then
            tsk.GblFunc_Add_Event("Charges Credited for the cause of the write off.", String.Empty, TasksEvents.EventStatus.SingleEvent, GlobalCRM.CurrentCaseID, TasksEvents.EventTypes.EventCase)

            Dim InvoiceNo As Long = Accounts.CreateInvoice(GlobalCRM.CurrentCaseID, GlobalCRM.CurrentCompanyID, GlobalCRM.CurrentCandidateID, Now, GlobalCRM.CurrentConName)
            If InvoiceNo = 0 Then
                CommonFuncs.DisplayMessage("Error creating invoice!", CommonDialog.CustomDialogIcons.Information, "Error")
                Exit Sub
            End If
            GlobalCRM.CurrentInvoiceId = InvoiceNo
            'Add the charges to the invoice using where clause from above
            Dim charges(1) As Long
            charges(0) = chargeId
            If Not Accounts.UpdateChargesAsInvoiced(GlobalCRM.CurrentCaseID, InvoiceNo, charges, False) Then
                Exit Sub
            End If
            tsk.GblFunc_Add_Event("Charges Invoiced for the cause of the write off.", String.Empty, TasksEvents.EventStatus.SingleEvent, GlobalCRM.CurrentCaseID, TasksEvents.EventTypes.EventCase)
        Else
            Exit Sub
        End If
        RefreshLists()
    End Sub
End Class
